package org.bl.chat.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import org.apache.catalina.User;
import org.bl.chat.common.exception.BusinessesException;
import org.bl.chat.dao.ChannelDao;
import org.bl.chat.dao.UserDao;
import org.bl.chat.model.dto.ChannelSaveDTO;
import org.bl.chat.model.po.ChannelDO;
import org.bl.chat.model.po.UserDO;
import org.bl.chat.model.vo.ChannelVO;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import static org.springframework.data.mongodb.core.query.Criteria.where;

@Service
public class UserService {

    @Resource
    private UserDao userDao;

    @Resource
    private MongoTemplate mongoTemplate;

    public UserDO getUser(String ip) {
            // 获取当前用户IP
            Optional<UserDO> userDO = userDao.findByIp(ip);
            UserDO user;
            if(userDO.isPresent()){
                user = userDO.get();
                user.setOnline(true);
                userDao.save(user);
            }else{
                user = new UserDO();
                user.setId(IdUtil.nanoId());
                user.setIp(ip);
                user.setId(IdUtil.nanoId());
                user.setUsername("未知用户");
                user.setOnline(true);
                user.setChannelId("68fcb36b55b669333e8277ac");
                userDao.save(user);
            }
            return user;
    }

    public List<UserDO> findByIsOnline(boolean b) {
        return userDao.findByIsOnline(b);
    }

    public void upUserName(String ip, String sender) {
        Query query = new Query(where("ip").is(ip));
        // 构造更新条件
        Update update = new Update().set("username", sender);
        // 执行更新操作
        mongoTemplate.updateFirst(query, update, UserDO.class);
    }
}
